/*
 Copyright 2009 Christian Sprecher

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

import net.miginfocom.swing.MigLayout
import javax.jcr.PropertyType
import javax.imageio.ImageIO
actions {
    action(id: 'savePropertyAction',
            name: "Save Property",
            closure: controller.saveProperty,
    )
    action(id: 'toggleModeAction',
            name: "Edit",
            closure: controller.toggleMode,
    )
}

def mode = model.mode
def values = []
def fileMode = false

panel(parentPanel, layout: new MigLayout("fill, insets -8 -8 0 -8 "), constraints:"grow, width max, height max") {
    //label(model.property.name)
    panel(id:'valuePanel', layout: new MigLayout("fill, insets 0"), constraints:"grow, width max, height max") {
          createViewer(property)
    }
    if(mode!=model.DISPLAY_MODE) {
        panel(layout: new MigLayout('wrap, insets 0' ,'[|]'), constraints: 'south') {
            button('Edit', id: 'modeButton', constraints: 'left, sg', action:toggleModeAction)
            button('Save', id:'saveButton', enabled:false, constraints: 'left, sg', action:savePropertyAction)
            saveButton.enabled = false
        }
    }
}
//TODO: not really MVC
def retrieveValues() {
    def result = []
    if(property.definition.multiple) {
        for(i in 0..values.size()-1) {
            result << retrieveOneValue(values[i])
        }
    }else {
        result << retrieveOneValue(values[0])
    }
    return result
}

def retrieveOneValue(value) {
    def result
    if(fileMode) {
        //as stream
        result = value
    }else {
        result = value.text
    }
    return result
}

def createEditor(property) {
    values = []
    fileMode = false
    def result
   if(property.definition.isMultiple()) {
//       panel(id:'valuePanel', layout: new MigLayout("fill, insets 10, top, left")) {
           result = panel(layout: new MigLayout("fill"), constraints:"grow, width max, height max") {
          // scrollPane(constraints: 'spany 2, grow,  height max, width max') {

               tabbedPane(id:'valuesPane', constraints: 'grow,  height max, width max'){
                  property.values.eachWithIndex { value,i ->
                      //panel(title: "${i+1}", constraints:'grow, height max, width max') {
                      scrollPane(title: "${i+1}", constraints:"grow, width max, height max") {
                          createOneEditor(property,value,i)
                      }
                  }
               }
           //}
           panel(layout: new MigLayout('fill, insets 0, gap 0'), constraints: 'wrap, top') {

               button('Add', constraints: 'sg, wrap, top', actionPerformed: {
                   valuesPane.add(createOneEditor(property, null), valuesPane.selectedIndex+1)
                   valuesPane.selectedIndex ++
                   valuesPane.setTitleAt(valuesPane.selectedIndex,"new")
               })
               button('Remove ', constraints: 'sg, wrap, top', actionPerformed: {
                   values.remove(valuesPane.selectedIndex)
                   valuesPane.remove(valuesPane.selectedIndex)
               })
           }
       }
   }  else {
       result = panel(layout: new MigLayout("fill"), constraints:"grow, width max, height max") {
            scrollPane(constraints:"grow, width max, height max") {
                createOneEditor(property, property.value)
            }
       }
   }
    return result
}


def createOneEditor(property, value, mvpIndex = 0) {
    def name = "propertyValue"
    if(property.type == PropertyType.BINARY/* && property.name != "jcr:data"*/) {
        def dropZone = panel(id:'dropZone', constraints: 'grow, height max, width max') {
            label('Drop File here', id:'dropText', constraints: 'grow, height max, width max')
        }
        if(property.definition.multiple) {
            values[mvpIndex]=property.values[mvpIndex].stream
        }else{
            values[0]=property.value.stream            
        }
        new FileDrop( dropZone, { files ->
            fileMode = true
            def file = files[0]
            //only one file supported atm
            int index = 0
            if(property.definition.multiple) { index = valuesPane.selectedIndex }
            values[index] = new FileInputStream(file)
            dropText.text = "Currently dropping ${file.canonicalPath}"
        } as FileDrop.Listener)
        return dropZone
    }

    if(property.type == PropertyType.BOOLEAN) {
        def result = panel {
            values << buttonGroup(id:name)
            value = value?:true
            radioButton('true', buttonGroup :propertyValue, selected:value)
            radioButton('false', buttonGroup :propertyValue, selected:!value)
        }
        return result
    }

        result = textArea(id:name, text: value?.getString(), columns:50, rows:20,constraints: 'grow, height max, width max')
        values << result
        new FileDrop( result, { files ->
            result.text = new File(files[0].canonicalPath).text
        }
        as FileDrop.Listener)
       return result

}

def createViewer(property) {
    def result
    if(property.definition.isMultiple()) {
        result = panel(layout: new MigLayout("fill"), constraints:"grow, width max, height max") {
            tabbedPane(constraints: 'grow,  height max, width max'){
               property.values.eachWithIndex { value,i ->
                   scrollPane(title: "${i+1}", constraints:"grow, width max, height max") {
                       createOneViewer(property,value)
                   }
               }
            }
        }
    }  else {
        result = panel(layout: new MigLayout("fill"), constraints:"grow, width max, height max") {
            scrollPane(constraints:"grow, width max, height max") {
                createOneViewer(property, property.value)
            }
        }
    }
    return result
}

def createOneViewer(property, value) {
    if(property.name == "jcr:data") {
        def mimeType = property.parent.getProperty("jcr:mimeType").getString()
        def result = createViewerForMimeType(mimeType, value)
        if(result) return result
    }
    if(value.type == PropertyType.BOOLEAN) {
        return label(value.getString())
    }
    return textArea(text: value.getString(),editable:false, columns:50, rows:20, constraints:"grow, width max, height max")
}

def createViewerForMimeType(mimeType, value) {
    def result

    if(mimeType.startsWith("image")) {
       //def panel = panel()
       def image = ImageIO.read(value.stream)
       result = jximagePanel(id:'dropZone', image:image, constraints:"grow, width max, height max")
    }
    return result
}